﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using Controllers;
using Infrastructure.DataTypes;
using Infrastructure;


namespace RecommenderSystem
{
    public partial class LogIn : Form
    {
        string m_user;
        string m_userID;
        Dispatcher m_cont;
        private BackgroundWorker bw;
        string m_dataSource;
        MainForm m_frm;
        bool flag;
        public LogIn()
        {
            InitializeComponent();
            m_cont = new Dispatcher();
            m_user = null;
            m_userID = null;
            flag = true;
            bw = new BackgroundWorker();
            bw.WorkerReportsProgress = true;
            bw.WorkerSupportsCancellation = true;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            LoadData();
        }

        public void LoadData()
        {
            m_user = null;
            comboBox1.DataSource = m_cont.dataSource();
            comboBox1.SelectedIndex = 0;
            
        }


        private void buttonLogIn_Click(object sender, EventArgs e)
        {
            string active_user = textBoxUser.Text;
            m_user = active_user;
            //progress bar event raiser, timer start.
            // myTimer.Start();



            if (active_user.Length > 0)
            {
                if (!File.Exists(textBoxUser.Text + ".txt"))
                {
                    MyMessageBox msg = new MyMessageBox("User name not found. \n Please register. ", "Unauthorized user ");
                    msg.ShowDialog();

                }
                else
                {
                    linkLabelNewUser.Visible = false;
                    buttonLogIn.ForeColor = Color.Gray;
                    //setting the progress bar to visible and other controls to invisible.
                    showProgressBar();
                    m_dataSource = comboBox1.Text;
                    Cursor = Cursors.WaitCursor;
                    if (comboBox1.Text == "MovieLens 1M")
                        progressBar1.Maximum = 20803000;
                    if (comboBox1.Text == "MovieLens 100K")
                        progressBar1.Maximum = 208030;

                    //activating the worker thread for parser 
                    bw.RunWorkerAsync();
                }

            }
            else
            {
                // MessageBox.Show("Please insert User name");
                MyMessageBox msgBox = new MyMessageBox("Please insert User name.", "Enter Name");
                msgBox.ShowDialog();
            }

        }


        #region Background Worker events

        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            m_cont.BackgroundWorker = bw;
            m_cont.LoadData(m_dataSource, m_user, m_userID);

        }
        private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {

            // update the progress bar
            if (progressBar1.Value == progressBar1.Maximum)
            {
               // progressBar1.Value = 0;
               // progressBar1.RightToLeft = progressBar1.RightToLeft == RightToLeft.No ? RightToLeft.Yes : RightToLeft.No;
            }
            //if(progressBar1.Style=
            if (!(progressBar1.Style == ProgressBarStyle.Marquee))
                this.progressBar1.PerformStep();



        }
        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

            progressBar1.Value = progressBar1.Maximum;
            //System.Threading.Thread.Sleep(1000);
            this.Cursor = Cursors.Default;
            readFromFile(m_user + ".txt");
            if (m_userID == null)
            {
                flag = true;
                User<Discrete> nUser = m_cont.GenerateUserID();
                m_userID = nUser.UserID;
                writeToFile(m_user + "|" + nUser.UserID, m_user+".txt");
            }
            else
            {
                flag = false;
            }

            m_cont.LoadDataOfLogInUser(m_dataSource, m_user, m_userID);
            this.m_frm = new MainForm(m_cont, m_user, m_userID, m_dataSource, flag);
            this.Hide();
            myTimer.Stop();

            ////////////////////////


            string active_user = textBoxUser.Text;
            m_dataSource = comboBox1.Text;
            // cont.loadData(dataSource);
            m_frm.ShowDialog();


            this.Close();


        }




        #endregion






        /// <summary>
        /// read from file to save the last data source selection
        /// </summary>
        /// <param name="dataSetName"></param>
        private void readFromFile(string file)
        {
            string ans = " ";
            try
            {
                StreamReader read = new StreamReader(file);
                ans = read.ReadLine().Trim();
                if (ans.Contains('|'))
                {
                    m_user = ans.Split('|')[0];
                    m_userID = ans.Split('|')[1];
                }
                else
                {
                    m_user = ans;
                    m_userID = null;
                }
                
                read.Close();
            }
            catch (Exception)
            {


                throw;
            }


        }






        /// <summary>
        ///  write to file that save the last data source selection
        /// </summary>
        /// <param name="dataSetName"></param>
        private void writeToFile(string data, string file)
        {
            try
            {
                StreamWriter SW;
                SW = File.CreateText(file);
                SW.WriteLine(data);
                SW.Close();
            }
            catch (Exception)
            {


            }




        }




        /// <summary>
        /// setting the page to the progress bar look
        /// </summary>
        private void showProgressBar()
        {
            label1.Visible = false;
            label2.Visible = false;
            textBoxUser.Visible = false;
            comboBox1.Visible = false;
            buttonLogIn.Enabled = false;


            labelWaitLoading.Visible = true;
            progressBar1.Visible = true;
            progressBar1.BringToFront();
        }







        private void myTimer_Tick(object sender, EventArgs e)
        {
            bw.ReportProgress(1);
        }


        private void linkLabelNewUser_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            AddNewUser newUserFRM = new AddNewUser();
            newUserFRM.ButtonClicked += new ButtonLogInEventHandler(newUserFRM_ButtonClicked);
            newUserFRM.ShowDialog();
        }


        private void newUserFRM_ButtonClicked(string user)
        {
            this.m_user = user;
            this.textBoxUser.Text = user;
            writeToFile(m_user, m_user + ".txt");
            flag = true;
        }


        private void textBoxUser_Click(object sender, EventArgs e)
        {
            textBoxUser.Focus();
        }


        private void LogIn_Load(object sender, EventArgs e)
        {


        }


        private void progressBar1_Click(object sender, EventArgs e)
        {


        }
    }
}